var express = require('express')
// 导入 uuid
var uuid = require('uuid')
var multipart=require('connect-multiparty');
var fs = require('fs')
var multipartMidd=multipart();
// 引入 md5 加密模块
var md5 = require('md5');

// 导入数据库工具类
var dbPromise = require('../utils/dbUtil')

var router = express.Router()

// 添加文章
router.post("/add/article",multipartMidd,async function(req, res){
    // 获取请求体参数
    const reqBody = req.body
    if(req.body=={}){
        return res.status(500).send({success:false})
    }
    console.log(reqBody)
    // console.log(reqBody)
    console.log(req.files)

    // 构建添加参数
    let obj = {
        // 生成唯一id
        id:uuid.v4(),
        type:reqBody.type,
        title:reqBody.title,
        user_id:reqBody.user_id,
        content:reqBody.content,
        created_time:reqBody.created_time,
    }

    // 获取tags
    if(reqBody.tags){
        let tags = eval(reqBody.tags)
        tags.forEach(item=>{
            // 添加 tags 和 文章id 的记录
            dbPromise('INSERT INTO topic_map(article_id, topic_id) values(?, (SELECT id from topic where name=?))',[obj.id,item])
            .then(result=>{
                // heat 的值加1
                return  dbPromise('update topic set heat=heat+1 where name=?',[item])
            })
            .catch(err=>{
                console.log(err)
                return res.status(500).send({success:false})
            })
           
        })
    }
    
    // 如果有添加图片
    if(req.files.pic_url != undefined){
        obj.pic_url = await writeFilePromise(req.files.pic_url,"./public/cover/")
    }
    let result =  await insertArticlePromise()  
    console.log(result)
    res.send({success:true})




    // 写文件 promise
    // function writeFilePromise(){
    //     return new Promise(resolve=>{
    //         let file = req.files.pic_url
    //         // 将临时目录中的文件移动到cover
    //         var readStream=fs.createReadStream(file.path);
    //         var writeStream=fs.createWriteStream("./public/cover/"+obj.id+file.name);
    //         readStream.pipe(writeStream);
    //         readStream.on('end',function(){
    //             fs.unlinkSync(file.path);
    //             // 将路径添加到reqBody中
    //             resolve(obj.id+file.name)
    //         });
    //     })
    // }

    // 操作数据库 promise
    function insertArticlePromise(){
        return new Promise(resolve=>{
            // 添加到数据库中
            dbPromise("INSERT INTO article set ?",obj)
            .then(result=>{})
            .catch(err=>{
                return res.status(500).send({success:false})
            })
        })
    }
    
})

// 获取所有的文章，分页查询
router.get('/query/allarticle', function(req, res){
    let {type,offset,pageSize} = req.query
    if(isNull(offset,pageSize)){
        return res.status(500).send({success:false})
    }
    offset = parseInt(offset,10)
    pageSize = parseInt(pageSize,10)
    // 查询数据库获取所有的数据
    if(type != null){
        let sql = "SELECT * FROM article where type=? ORDER BY created_time desc  limit ?,?"
        dbPromise(sql,[type,offset,pageSize])
        .then(result=>{
            result=result.map(async item=>{
                // 获取用户信息
                let user = await getUserById(item.user_id)
                let tags = await getArticleTags(item.id)
                let resultData = {
                    id:item.id,
                    type:item.type,
                    title:item.title,
                    user:user,
                    content:item.content,
                    createdTime:item.created_time,
                    picUrl:item.pic_url,
                    tags:tags
                }
                return resultData
            })

            Promise.all(result).then(data=>{
                // console.log(data)
                res.send(data)
            })
        })
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})
        })
    }else{
        let sql = "SELECT * FROM article ORDER BY created_time desc limit ?,?"
        dbPromise(sql,[offset,pageSize])
        .then(result=>{
            // console.log(result)
            result=result.map(async item=>{
                // 获取用户信息
                let user = await getUserById(item.user_id)
                let tags = await getArticleTags(item.id)
                let resultData = {
                    id:item.id,
                    type:item.type,
                    title:item.title,
                    user:user,
                    content:item.content,
                    createdTime:item.created_time,
                    picUrl:item.pic_url,
                    tags:tags
                }
                return resultData
            })

            Promise.all(result).then(data=>{
                // console.log(data)
                res.send(data)
            })
        }) 
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})
        })
    }

})

// 根据id查找文章
router.get('/query/article',function(req, res){
    // 获取id
    const id = req.query.id
    if(isNull(id)){
        return res.status(500).send({success:false})
    }
    // 查询数据库
    dbPromise("SELECT * FROM article where id=?",[id])
    .then(async result=>{
        // 用户信息
        let user = await getUserById(result[0].user_id)
        result = {
            id:result[0].id,
            type:result[0].type,
            title:result[0].title,
            user:user,
            content:result[0].content,
            createdTime:result[0].created_time,
            picUrl:result[0].pic_url
        }
        // console.log(result)
        res.send(result)
    })
    .catch(err=>{
        console.log(err)
        return res.status(500).send({success:false})
    })
})

// 根据用户id查询文章
router.get('/query/article/user',function(req, res){
    let {id,offset,pageSize} = req.query
    if(isNull(id,offset,pageSize)){
        return res.status(500).send({success:false})
    }
    offset = parseInt(offset,10)
    pageSize = parseInt(pageSize,10)
    // 查询数据库
    if(id != null){
        dbPromise("SELECT * FROM article where user_id=? ORDER BY created_time desc  limit ?,?",[id,offset,pageSize])
        .then(result=>{
            result=result.map(async item=>{
                // 获取用户信息
                let user = await getUserById(item.user_id)
                let tags = await getArticleTags(item.id)
                let resultData = {
                    id:item.id,
                    type:item.type,
                    title:item.title,
                    user:user,
                    content:item.content,
                    createdTime:item.created_time,
                    picUrl:item.pic_url,
                    tags:tags
                }
                return resultData
            })
    
            Promise.all(result).then(data=>{
                console.log(data)
                return res.send(data)
            })
        })
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})
        })
    }else{
        return res.status(500).send({success:false})
    }
})

// 根据id删除文章
router.post('/delete/article', function(req, res){
    const id = req.body.id
    if(isNull(id)){
        return res.status(500).send({success:false})
    }
    // 操作数据库删除文章
    dbPromise('DELETE FROM article where id=?',[id])
    .then(result=>{
        console.log(result[0])
        res.send(result[0])
    })
    .catch(err=>{
        return res.status(500).send({success:false})
    })
})

// 根据id修改文章
router.post('/update/article',multipartMidd,async function(req, res){
    let reqBody = req.body
    if(isNull(reqBody.id, req.files)){
        return res.status(500).send({success:false})
    }
    let pic_url = null

    // 获取tags
    if(reqBody.tags){
        let tags = eval(reqBody.tags)
        // 清空原有的tags
        dbPromise('DELETE FROM topic_map where article_id=?',[reqBody.id])
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})     
        })
        tags.forEach(item=>{
            // 添加 tags 和 文章id 的记录
            dbPromise('INSERT INTO topic_map(article_id, topic_id) values(?, (SELECT id from topic where name=?))',[reqBody.id,item])
            .then(result=>{
                // heat 的值加1
                return  dbPromise('update topic set heat=heat+1 where name=?',[item])
            })
            .catch(err=>{
                console.log(err)
                return res.status(500).send({success:false})
            })
            
        })
    }

    if(req.files.pic_url != null){
        pic_url = await writeFilePromise(req.files.pic_url, './public/cover/')
        console.log(req.files.pic_url)
        // 添加到数据库中
        dbPromise("UPDATE article set title=?,type=?, content=?, created_time=?, pic_url=? where id=?",[reqBody.title, reqBody.type, reqBody.content, reqBody.created_time, pic_url, reqBody.id])
        .then(result=>{
            console.log(result)
            return res.send({success:true})    
        })
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})
        })
    }else{
        // 添加到数据库中
        dbPromise("UPDATE article set title=?,type=?, content=?, created_time=? where id=?",[reqBody.title, reqBody.type, reqBody.content, reqBody.created_time, reqBody.id])
        .then(result=>{
            console.log(result)
            return res.send({success:true})
        })
        .catch(err=>{
            console.log(err)
            return res.status(500).send({success:false})
        })
    }


    // // 写文件 promise
    // function writeFilePromise(){
    //     return new Promise(resolve=>{
    //         let file = req.files.pic_url
    //         // 将临时目录中的文件移动到cover
    //         var readStream=fs.createReadStream(file.path);
    //         var writeStream=fs.createWriteStream("./public/cover/"+reqBody.id+file.name);
    //         readStream.pipe(writeStream);
    //         readStream.on('end',function(){
    //             fs.unlinkSync(file.path);
    //             // 将路径添加到reqBody中
    //             resolve(reqBody.id+file.name)
    //         });
    //     })
    // }

})

// 用户登录
router.post('/login',function(req, res){
    // 获取请求参数
    let reqBody = req.body
    console.log(reqBody)
    let {username, password} = reqBody
    if(isNull(username, password)){
        return res.status(500).send({success:false})
    }
    // md5加密
    password = md5(password)
    // 查询数据库
    dbPromise("SELECT * FROM user where username=? and password=?",[username,password])
    .then(result=>{
        let length = JSON.parse(JSON.stringify(result)).length
        if(length  == 0){
            return res.status(500).send("error")
        }
        else{
            console.log(result[0])
            return res.send(result[0])
        }
    })
    .catch(err=>{
        console.log(err)
        return res.status(500).send(err)
    })
})

// 用户注册
router.post('/register',function(req, res){
    // 获取请求参数
    let reqBody = req.body
    reqBody.password = md5(reqBody.password)
    params = {
        ...reqBody,
        // 使用 uuid 生成id
        id:uuid.v4(),
        // 默认性别保密
        gender:-1,
    }
    // 操作数据库添加字段
    dbPromise("INSERT INTO user set?", params)
    .then(result=>{
        console.log(result)
        res.send({success:true})
    })
    .catch(err=>{
        return res.status(500).send("error")
    })
})

// 查询所有的话题
router.get('/query/alltopic', (req, res)=>{
    // 查询数据库获取所有数据
    dbPromise('SELECT * FROM topic')
    .then(result=>{
        console.log(result)
        res.send(result)
    })
    .catch(err=>{
         return res.status(500).send({success:false})
    })
})

// 根据话题id查询所有的文章，分页
router.get('/query/withtopic',(req, res)=>{
    // 获取 topic id 
    let {id, offset, pageSize} = req.query
    if(isNull(id,offset,pageSize)){
        return res.status(500).send({success:false})
    }
    offset = parseInt(offset)
    pageSize = parseInt(pageSize)
    let sql = 'select * from topic join topic_map on topic.id=topic_map.topic_id join article on topic_map.article_id=article.id join user on user.id=article.user_id where topic.id=? limit ?,?'
    dbPromise({sql:sql,nestTables:true}, [id, offset,pageSize])
    .then(result=> {
        console.log(result)
        // 构建返回参数
        let ret = result.map(async item=>{
            let tags = await getArticleTags(item.article.id)
            console.log(tags)
            let val = {
                id:item.article.id,
                type:item.article.type,
                title:item.article.title,
                user:item.user,
                content:item.article.content,
                createdTime:item.article.created_time,
                picUrl:item.article.pic_url,
                tags:tags
            }
            return val
        })
        Promise.all(ret).then(data=>{
            // console.log(data)
            res.send(data)
        })
    })
    .catch(err=>{
        return res.status(500).send({success:false})
    })

})

// 修改用户信息
router.post('/update/user',multipartMidd,async function(req, res){
    let {id,username,password,gender} = req.body
    let avatarFile = req.files.avatar
    let sql = 'UPDATE user set '
    let dataArray = []
    if(username != null){
        sql += 'username=? '
        dataArray.push(username)
    }
    if(password != null){
        sql += ',password=? '
        // md5 加密
        dataArray.push(md5(password))
    }
    if(gender != null){
        sql += ',gender=? '
        // md5 加密
        gender = parseInt(gender, 10)
        dataArray.push(gender)
    }
    let avatar_url
    if(avatarFile!=null){
        sql += ',avatar=? '
        // 写文件
        avatar_url = await writeFilePromise(avatarFile,"./public/avatar/")
        dataArray.push(avatar_url)
    }
    sql += 'where id=?'
    dataArray.push(id)
    console.log(sql,dataArray)
    dbPromise(sql,dataArray)
    .then(result=>{
        console.log(result)
        res.send(avatar_url)
    })
    .catch(err=>{
        console.log(err)
        return res.status(500).send({success:false})
    })


    
})

// 获取用户信息
router.get('/query/user',(req, res)=>{
    // 获取参数
    let {id} = req.query
    if(isNull(id)){
        return res.status(500).send({success:false})
    }
    // 查询数据库
    dbPromise('SELECT * FROM user WHERE id=?',[id])
    .then(result=>{
        // 移除密码
        delete result[0].password
        res.send(result[0])
    })
    .catch(err=>{
        return res.status(500).send({err})
    })
})

// 关注用户
router.get('/subscribe',(req,res)=>{
    let {userId, targetId} = req.query
    if(isNull(userId, targetId)){
        return res.status(500).send({success:false})
    }
    let target = {
        user_id:userId,
        target_user_id:targetId
    }
    let sql = 'INSERT INTO subscribe SET ?'
    dbPromise(sql, [target])
    .then(result=>{
        res.send(result)
    })
    .catch(err=>{
        res.status(500).send(err)
    })
})

// 取消关注
router.post('/delete/subscribe',(req,res)=>{
    // 获取参数
    const {userId, targetId} = req.body
    if(isNull(userId,targetId)){
        return res.status(500).send({success:false})
    }
    // 更新记录
    dbPromise("delete from subscribe where user_id=? and target_user_id=?",[userId, targetId])
    .then(result=>{
        return res.send(result)
    })
    .catch(err=>{
        return res.send(err)
    })

})

// 根据用户id查询关注的用户数组
router.get('/query/subscribe', (req, res)=>{
    let {userId,offset,pageSize} = req.query
    if(isNull(userId,offset,pageSize)){
        return res.status(500).send({success:false})
    }
    offset = parseInt(offset)
    pageSize = parseInt(pageSize)
    let sql = 'select * from user as u1 join subscribe on u1.id=subscribe.target_user_id join user as u2 on subscribe.user_id=u2.id where u2.id=? limit ?,?' 
    dbPromise({sql:sql,nestTables:true},[userId, offset, pageSize])
    .then(result=>{
        // 构建返回的对象
        result = result.map(item=>{
            let ret = {
                id:item.u1.id,
                username:item.u1.username,
                gender:item.u1.gender,
                avatar:item.u1.avatar
            }
            return ret
        })
        console.log(result)
        res.send(result)
    })
    .catch(err=>{
        res.status(500).send(err)
    })
})

// 收藏文章
router.get('/collection/articles', (req, res)=>{
    // 获取参数
    let {userId, articleId} = req.query
    if(isNull(userId, articleId)){
        return res.status(500).send({success:false})
    }
    let data = {
        user_id:userId,
        article_id:articleId
    }
    // 添加记录
    dbPromise('INSERT INTO collection SET ?',[data])
    .then(result=>{
        res.send(result)
    })
    .catch(err=>{
        res.status(500).send(err)
    })
})

// 获取收藏列表
router.get('/query/collections', (req,res)=>{
    // 获取参数
    let {userId, offset, pageSize} = req.query
    if(isNull(userId,offset,pageSize)){
        return res.status(500).send({success:false})
    }
    offset = parseInt(offset)
    pageSize = parseInt(pageSize)
    // 添加记录
    let sql = 'select * from article join collection on article.id=collection.article_id join user on user.id=collection.user_id where user.id=? limit ?,?'
    dbPromise({sql:sql,nestTables:true },[userId,offset,pageSize])
    .then(result=>{
        result = result.map(async item=>{
            let tags = await getArticleTags(item.article.id)
            let ret = {
                id:item.article.id,
                type:item.article.type,
                title:item.article.title,
                user:item.user,
                tags:tags,
                content:item.article.content,
                createdTime:item.article.created_time,
                picUrl:item.article.pic_url,
            }
            return ret
        })
        Promise.all(result).then(data=>{
            // console.log(data)
            res.send(data)
        })
    })
    .catch(err=>{
        res.status(500).send(err)
    })
})

// 取消收藏
router.post("/delete/collection", function(req, res){
    // 获取参数
    const {userId, articleId} = req.body
    if(isNull(userId,articleId)){
        return res.status(500).send({success:false})
    }
    // 更新记录
    dbPromise("delete from collection where article_id=? and user_id=?",[articleId, userId])
    .then(result=>{
        return res.send(result)
    })
    .catch(err=>{
        return res.send(err)
    })
    
})


//根据id查询用户
function getUserById(id){
    return new Promise((resolve, reject) =>{
        dbPromise("SELECT * FROM user where id=?",[id])
        .then(result=>{
            resolve(result[0])
        })
        .catch(err=>{
            reject(err)
        })
    })
}

// 根据文章id查询标签
function getArticleTags(id){
    return new Promise((resolve,reject)=>{
        dbPromise("select * from topic_map JOIN topic on topic.id=topic_map.topic_id where article_id = ?",[id])
        .then(result=>{
            // result = result.map(item=>{
            //     return item.name
            // })
            resolve(result)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

// 判断是否全为非空对象
function isNull(...objs){
    let result = false
    objs.forEach(item=>{
        if(item==undefined){
            result = true
            return
        }
    })
   return result
}

// 写文件 promise
function writeFilePromise(file,path){
    return new Promise(resolve=>{
        // 将临时目录中的文件移动到cover
        var readStream=fs.createReadStream(file.path);
        var writeStream=fs.createWriteStream(path+file.name);
        readStream.pipe(writeStream);
        readStream.on('end',function(){
            fs.unlinkSync(file.path);
            // 将路径添加到reqBody中
            resolve(file.name)
        });
    })
}
module.exports = router
 